package org.xiaov.core.factory;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.xiaov.common.bean.AutoCodeInfo;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p>
 * 描述：数据库的工厂类
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/9/16 22:28
 */
@Data
@Slf4j
public class DatabaseFactory {

    DataSource dataSource;

    public DatabaseFactory(AutoCodeInfo autoCodeInfo) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(autoCodeInfo.getDriverClassName());
        dataSource.setUrl(autoCodeInfo.getDbUrl());
        dataSource.setDriverClassName(autoCodeInfo.getDriverClassName());
        dataSource.setUsername(autoCodeInfo.getDbUsername());
        dataSource.setPassword(autoCodeInfo.getDbPassword());
        //用来检测连接是否有效
        dataSource.setValidationQuery("SELECT 1");
        //申请连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能
        dataSource.setTestOnBorrow(false);
        //归还连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能
        dataSource.setTestOnReturn(false);
        //申请连接的时候检测，如果空闲时间大于timeBetweenEvictionRunsMillis，执行validationQuery检测连接是否有效。
        //如果检测失败，则连接将被从池中去除
        dataSource.setTestWhileIdle(true);
        dataSource.setTimeBetweenEvictionRunsMillis(600000);
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(10);
        this.dataSource = dataSource;
    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
